<template>
    <div>
        <a-upload

                list-type="picture-card"
                class="avatar-uploader"
                :show-upload-list="false"

                :before-upload="beforeUpload"
                @change="handleChange"
                :customRequest="customRequest"
        >


            <img v-if="imageUrl" :src="imageUrl"
                 alt="avatar"
                 class="avatar-img" />
            <div v-else>
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">上传头像</div>
            </div>
        </a-upload>

    </div>

</template>
<script>
 function  upStaffAvatar(e) {
    console.log(e);
 }

    export default {

        data() {
            return {
                //避免组件冲突
                avatarUrl:null,
                imageUrl:"",
                loading: false,

            }

        },


        methods: {
            //自定义上唇方法
            customRequest (data) {
                const formData = new FormData();
                //值要data里面的file对象 其他对象不要了
                // formData.append('参数名称', "参数值")
                formData.append('file', data.file)

                console.log(data.file);
                upStaffAvatar(formData).then((res) => {
                    this.loading = false;
                    if(res.code===0){
                        this.imageUrl = res.data.url;
                        //通知父组件 更新图片地址
                        this.$emit('avatarUploadCallback', res.data.url);
                    }

                })



            },

            //监听上传状态  uploading 开始
            handleChange(info) {
                if (info.file.status === 'uploading') {
                    this.loading = true;
                }

            },
            //上传之前数据检查
            beforeUpload(file) {
                const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
                if (!isJpgOrPng) {
                    this.$message.error('只允许上传JPG格式的图片文件');
                }
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    this.$message.error('单个文件图片不能超过 2MB!');
                }
                return isJpgOrPng && isLt2M;
            },
        },

        watch:{
            //如果父组件传递的头像路径发生变化 刷新组件显示地址
            avatarUrl(val) {
                this.imageUrl =val;
            }
        }



    };
</script>
<style>
    .avatar-img{  width: 128px;
        height: 128px;
        overflow: hidden;}
    .avatar-uploader > .ant-upload {
        width: 128px;
        height: 128px;
    }
    .ant-upload-select-picture-card i {
        font-size: 32px;
        color: #999;
    }

    .ant-upload-select-picture-card .ant-upload-text {
        margin-top: 8px;
        color: #666;
    }
</style>